import React, { forwardRef, useImperativeHandle, useState } from 'react';
import FilePathBreadCrumb from './FilePathBreadCrumb';
import type { IFilePathBreadCrumbItem } from './FilePathBreadCrumb/interface';
import { IFilePathsParam, RefFn, RefFnParams } from './interface';

const firstFileBreadCrumb: IFilePathBreadCrumbItem = { key: '0', label: '全部文件' };

const FilePaths = forwardRef<RefFn, IFilePathsParam>((props, ref) => {
  const [filePaths, setFilePathes] = useState<IFilePathBreadCrumbItem[]>([]);
  const { onBreadCrumbClick } = props;
  // 点击文件路径
  const hanleBreadCrumbClick = (e: React.MouseEvent, item: IFilePathBreadCrumbItem) => {
    const { key } = item;
    let newFilePaths = filePaths;
    const pathIndex = newFilePaths.findIndex(
      (pathItem: IFilePathBreadCrumbItem, index: number) => pathItem.key === key,
    );
    newFilePaths.splice(pathIndex + 1);
    newFilePaths[newFilePaths.length - 1].disabled = true;
    if (newFilePaths.length === 1) {
      newFilePaths = [];
    }
    setFilePathes(newFilePaths);
    onBreadCrumbClick?.(e, key);
  };

  const onAddFilePaths = ({ resourceId, resourceName }: RefFnParams) => {
    if (!filePaths[0] || filePaths[0].key !== firstFileBreadCrumb.key) {
      filePaths.push(firstFileBreadCrumb);
    }
    filePaths[filePaths.length - 1].disabled = false;
    filePaths.push({ key: resourceId, label: resourceName, disabled: true });
    setFilePathes([...filePaths]);
  };

  const getFilePaths = () => {
    return filePaths;
  };
  const resetFilePaths = (paths: IFilePathBreadCrumbItem[]) => {
    setFilePathes([...paths]);
    // onBreadCrumbClick?.(paths.length ? paths[0].key : '');
  };
  useImperativeHandle(ref, () => ({
    onAddFilePaths,
    getFilePaths,
    resetFilePaths,
  }));

  // useImperativeHandle(ref, () => ({ onAddFilePaths: onAddFilePaths, filePaths: filePaths }));

  return <FilePathBreadCrumb items={filePaths} onClick={hanleBreadCrumbClick} />;
});

export default FilePaths;
